<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 通知栏全局组件 -->
      <PageTools>
        <template v-slot:after>
          <div>
            <el-button type="primary" @click="changeRouter">导入</el-button>
            <el-button type="danger" @click="exportDate">导出</el-button>
            <el-button type="primary" @click.native="addEmployee">+添加员工</el-button>
          </div>
        </template>
      </PageTools>
      <!-- 表格展示面板 -->
      <el-card>
        <el-table :data="employeesList" style="width: 100%">
          <el-table-column type="index" label="序号" width="50" header-align="center" />
          <el-table-column
            prop="username"
            label="姓名"
            width="120"
            header-align="center"
            align="center"
          />
          <el-table-column prop="staffPhoto" label="头像" width="200" header-align="center">
            <template slot-scope="{row}">
              <img v-imagerror="defaultImg" :src="row.staffPhoto || defaultImg" class="img" @click="showUrl(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" width="200" header-align="center" />

          <el-table-column prop="workNumber" label="工号" width="120" header-align="center" />

          <el-table-column prop="formOfEmployment" label="聘用方式" width="100" header-align="center">
            <template slot-scope="{row}">{{ row.formOfEmployment >= 2? '非正式':'正式' }}</template>
          </el-table-column>

          <el-table-column prop="departmentName" label="部门" width="120" header-align="center" />

          <el-table-column prop="correctionTime" label="入职时间" width="120" header-align="center">
            <template slot-scope="{ row }">{{ row.timeOfEntry | timeDate }}</template>
          </el-table-column>

          <el-table-column prop="formOfEmployment" label="状态" width="120" header-align="center" />

          <el-table-column fixed="right" label="操作" width="300" header-align="center">
            <template slot-scope="scope">
              <el-row type="flex" justify="space-around">
                <el-button type="text" size="small" @click="detail(scope.row.id)">查看</el-button>
                <el-button type="text" size="small" @click="handleClick(scope.row)">转正</el-button>
                <el-button type="text" size="small" @click="handleClick(scope.row)">调岗</el-button>
                <el-button type="text" size="small" @click="handleClick(scope.row)">离职</el-button>
                <el-button type="text" size="small" @click="allocator(scope.row)">角色</el-button>
                <el-button type="text" size="small" @click="delEmployee(scope.row.id)">删除</el-button>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="center" align="center">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changecurrentPage"
          />
        </el-row>
      </el-card>
      <!-- 添加员工弹出层 -->
      <addEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCanvas" center>
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色弹出层 -->
      <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { getEmployeesList, delEmployee } from '@/api/employees'
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import qrCode from 'qrcode'
import assignRole from './assign-role.vue'
export default {
  filters: {
    timeDate(val) {
      return moment(val).format('YYYY-MM-DD')
    }
  },
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      userId: null,
      page: {
        size: 10, // 每一页要展示多少条数据
        page: 1, // 当前页码
        total: 0 // 总条数
      },
      showRoleDialog: false, // 角色分配弹出层
      showCanvas: false, // 显示二维码弹窗
      defaultImg: require('@/assets/common/head.jpg'), // 图片错误时 显示的 头像
      showDialog: false,
      employeesList: [] // 员工列表，
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    async getEmployeesList() {
      // 获取员工列表
      const { rows, total } = await getEmployeesList(this.page)
      // console.log(rows)
      this.page.total = total
      this.employeesList = rows
    },
    //  根据id删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeesList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    //  跳转到员工详情页 把当前用户的id 传过去
    detail(id) {
      this.$router.push(`/detail/${id}`)
    },
    //  监听分页器改变
    changecurrentPage(newPage) {
      this.page.page = newPage
      this.getEmployeesList()
    },
    // 添加员工
    addEmployee() {
      this.showDialog = true
    },
    //   跳转到import 员工导入页面
    changeRouter() {
      this.$router.push('/import')
    },
    // 导出
    exportDate() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const { rows } = await getEmployeesList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader, // 复杂表头
          merges// 合并选项
        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      //  处理时间
      const obj = { 1: '正式', 2: '非正式' }
      return rows.map(item => {
        // item是一个对象  { mobile: 132111,username: '张三'  }
        return Object.keys(headers).map(key => {
          // 需要判断 字段
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            return obj[ item['formOfEmployment'] ] || '未知'
          }
          return item[headers[key]]
        })
      })
    },
    //  显示二维码
    showUrl(url) {
      if (url) {
        this.showCanvas = true
        this.$nextTick(() => {
          qrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户未上传图片')
      }
    },
    // 分配角色
    async  allocator(obj) {
      this.showRoleDialog = true
      await this.$refs.assignRole.getUserDetailById(obj.id)
      this.userId = obj.id
    }
  }
}
</script>

<style>
.cell{
  display: flex;
  justify-content: center;
  align-items: center;
}
.img{
  width: 50%;
  border-radius: 50%;
}
</style>
